/*
 *  Copyright 2012 SerGenis. All rights reserved.
 */
package com.sergenis.form;

import com.sergenis.beans.AbstractListSingleBinding;
import com.sergenis.swing.ListViewModel;
import java.util.Collection;
import java.util.List;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;

/**
 *
 * @author SerGenis
 */
public class JListWithFormBinding<E>
    extends AbstractListSingleBinding<E> {

    public JListWithFormBinding(JList<E> jlist, List<E> elements) {
	super(jlist.getSelectionModel(), elements);
	this.jlist = jlist;
	this.jlist.setModel(listModel);
    }
    private final JList<E> jlist;

    public void setElements(Collection<E> c) {
	this.listModel = new ListViewModel(c);
	jlist.setModel(listModel);
	//firePropertyChange("elements", null, c);
    }

    public JList<E> getJlist() {
	return jlist;
    }

    @Override
    public E getActive() {
	if (indexActive < 0) return null;
	return listModel.get(indexActive);
    }

    public void valueChanged(ListSelectionEvent e) {
	ListSelectionModel model = (ListSelectionModel) e.getSource();
	if (e.getValueIsAdjusting()) return;

	int minIndex = model.getMinSelectionIndex();
	setIndexActive(minIndex);
	firePropertyChange("active", null, getActive());
    }
}
